;
(function(window, $) {

    var emitter = {
        // 注册事件
        on: function(event, fn) {
            var handles = this._handles || (this._handles = {}),
                calls = handles[event] || (handles[event] = []);

            // 找到对应名字的栈
            calls.push(fn);

            return this;
        },
        // 解绑事件
        off: function(event, fn) {
            if (!event || !this._handles) this._handles = {};
            if (!this._handles) return;

            var handles = this._handles,
                calls;

            if (calls = handles[event]) {
                if (!fn) {
                    handles[event] = [];
                    return this;
                }
                // 找到栈内对应listener 并移除
                for (var i = 0, len = calls.length; i < len; i++) {
                    if (fn === calls[i]) {
                        calls.splice(i, 1);
                        return this;
                    }
                }
            }
            return this;
        },
        // 触发事件
        emit: function(event) {
            var args = [].slice.call(arguments, 1),
                handles = this._handles,
                calls;

            if (!handles || !(calls = handles[event])) return this;
            // 触发所有对应名字的listeners
            for (var i = 0, len = calls.length; i < len; i++) {
                calls[i].apply(this, args)
            }
            return this;
        }
    }

    function Timeline(opt) {
        console.log(opt, 'opt');

        $.extend(this, opt);
        this.con = this.con || $('body'); //在此节点插入
        this.timeArr = this.timeArr || []; //有录像的时间

        this._init(this.con)
    }

    Timeline.prototype = {
        _init: function(con) {
            this.el = this._createNode();
            con.append(this.el);
            this._draw();
            this._drawTime();

            this._initEvent();
        },
        _createNode: function() {
            return $('<canvas width="720" height="50"></canvas>')
        },
        _draw: function() {
            var ctx = this.el[0].getContext('2d');
            var gradient = ctx.createLinearGradient(0, 0, 720, 0);
            gradient.addColorStop("0", "white");
            gradient.addColorStop("0.5", "white");
            gradient.addColorStop("1.0", "white");
            ctx.fillStyle = gradient;
            ctx.strokeRect(0, 0, 720, 40);

            // 绘制刻度
            ctx.save();
            // ctx.translate(0.5, 0.5);
            ctx.beginPath()
            for (let i = 1; i < 25; i++) { // 大刻度，30px/h
                ctx.moveTo(30 * i, 40);
                ctx.lineTo(30 * i, 10);
            }
            for (let i = 1; i < 145; i++) { // 小刻度, 5px/10min
                ctx.moveTo(5 * i, 40);
                ctx.lineTo(5 * i, 30);
            }
            ctx.closePath();
            ctx.fillStyle = "#000"
            ctx.strokeStyle = "#000";
            ctx.stroke();


            // ctx.translate(-0.5, -0.5);

            // 绘制文字

            ctx.fillText('0:00', 0, 50);
            ctx.fillText('2:00', 60, 50);
            ctx.fillText('4:00', 120, 50);
            ctx.fillText('6:00', 180, 50);
            ctx.fillText('8:00', 240, 50);
            ctx.fillText('10:00', 300, 50);
            ctx.fillText('12:00', 360, 50);
            ctx.fillText('14:00', 420, 50);
            ctx.fillText('16:00', 480, 50);
            ctx.fillText('18:00', 540, 50);
            ctx.fillText('20:00', 600, 50);
            ctx.fillText('22:00', 660, 50);
            ctx.fillText('24:00', 720, 50);
        },
        _drawTime: function() {
            var _this = this;
            var ctx = this.el[0].getContext('2d');

            this.timeArr.forEach(element => {
                var begin = Math.floor((element.m_uBeginTime - _this.begintime) / 120);
                var end = Math.ceil((element.m_uEndTime - _this.begintime) / 120);
                var width = end - begin;

                ctx.fillStyle = "#FFA500";
                ctx.fillRect(begin, 0, width, 40);

            });
        },
        scale2time_format: function(x) {
            var hour = Math.floor(x * 2 / 60);
            var minute = x * 2 - hour * 60;
            return hour + ':' + (minute < 10 ? '0' + minute : minute);
        },
        _scale2time: function(x) {
            return this.begintime + x * 120;
        },
        _initEvent: function() {
            var _this = this;
            this.el[0].addEventListener('mousemove', function() {
                var x = event.clientX - this.getBoundingClientRect().left;
                var time = _this.scale2time_format(x.toFixed(0));
                _this.con.attr('title', time);
            });
            this.el[0].addEventListener('click', function() {

                var x = event.clientX - this.getBoundingClientRect().left;
                var time = _this._scale2time(x.toFixed(0));
                var localTime = _this.scale2time_format(x);
                _this.emit("start", { time, localTime });
            })

            //关闭鼠标右键默认事件
            $('#timeline1').bind("contextmenu", function() {
                return false;
            });
            this.el[0].addEventListener('mousedown', function(e) {
                //滚轮事件获取：调用播放下载

                if (2 == e.which) {
                    var x = event.clientX - this.getBoundingClientRect().left;
                    var time = _this._scale2time(x);

                    _this.emit("playdownload", time);
                }
                //右键事件获取：调用录像下载

                if (3 == e.which) {
                    var x = event.clientX - this.getBoundingClientRect().left;
                    var time = _this._scale2time(x);

                    _this.emit("downloadrecordfile", time);
                }

            })

        }
    }

    $.extend(Timeline.prototype, emitter);

    window.Timeline = Timeline; // 暴露给全局
})(window, window.jQuery)